const { useState } = React;

function LoginForm() {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!username || !password) {
            setError('请输入用户名和密码');
            return;
        }

        setLoading(true);
        setError('');

        try {
            console.log('Sending request to:', `${CONFIG.API_BASE_URL}${CONFIG.API_ENDPOINTS.ADMIN_LOGIN}`);
            const response = await fetch(`${CONFIG.API_BASE_URL}${CONFIG.API_ENDPOINTS.ADMIN_LOGIN}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            console.log('Response:', data);

            if (data.code === 200) {
                // 同时更新localStorage和全局状态
                CONFIG.state.setAdminToken(data.data.token);
                console.log('Login successful, token saved');
                // 跳转到管理页面
                window.location.href = '/admin/detail.html';
            } else {
                setError(data.message || '登录失败');
            }
        } catch (err) {
            console.error('Login error:', err);
            setError('网络错误，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="login-container">
            <h1 className="login-title">管理员登录</h1>
            <form className="login-form" onSubmit={handleSubmit}>
                <div className="form-item">
                    <label htmlFor="username">用户名</label>
                    <input
                        type="text"
                        id="username"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        placeholder="请输入用户名"
                        autoComplete="username"
                    />
                </div>
                <div className="form-item">
                    <label htmlFor="password">密码</label>
                    <input
                        type="password"
                        id="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder="请输入密码"
                        autoComplete="current-password"
                    />
                </div>
                <button 
                    type="submit" 
                    className="login-button"
                    disabled={loading}
                >
                    {loading ? '登录中...' : '登录'}
                </button>
                {error && <div className="error-message">{error}</div>}
            </form>
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('root')).render(<LoginForm />);
